/*
 * @Author: Jiraiya
 * @Date: 2020-05-04 23:23:21
 * @LastEditors: Jiraiya
 * @LastEditTime: 2020-05-07 15:37:46
 * @Description: 事务封装
 */
const {logger} = bee;

class TransactionConnection{

    constructor(conn){
        this._connection = conn; //连接
        this._isReleased = false; //改连接是否已释放
    }

    /**
     * @description:  query封装
     * @param {type} 
     * @return: 
     */
    query(sql, values){
        if( ! this._connection ){
            return Promise.reject('当前MySQL连接已经释放, 不能调用 query');
        }
        return new Promise( (resolve, reject) => {
            this._connection.query(sql, values, function(err, results, fields){
                if( err ){
                    return reject(err);
                }
                resolve({
                    results : results,
                    fields : fields
                });
            });
        });
    }

    /**
     * @description: 释放连接
     * @param {type} 
     * @return: 
     */
    release(){
        if( ! this._isReleased && this._connection ){
            this._connection.release();
            this._isReleased = true;
            this._connection = null;
            logger.info('连接已释放')
        }
    }

    /**
     * @description: 销毁连接
     * @param {type} 
     * @return: 
     */
    destroy(){
        if( this._connection ){
            this._connection.destroy();
            this._connection = null;
        }
    }

    /**
     * @description: 开始事务
     * @param {type} 
     * @return: 
     */
    beginTransaction(){
        if( ! this._connection ){
            return Promise.reject('当前MySQL连接已经释放, 不能调用 beginTransaction');
        }
        let that = this;
        return new Promise( (resolve, reject) => {
            this._connection.beginTransaction( function(err){
                if( err ){
                    return reject(err);
                }
                resolve(that);
            } );
        });
    }

    /**
     * @description: 提交事务
     * @param {type} 
     * @return: 
     */
    commit(){
        if( ! this._connection ){
            return Promise.reject('当前MySQL连接已经释放, 不能调用 commit');
        }
        let that = this;
        return new Promise( (resolve, reject) => {
            this._connection.commit( function(err){
                if( err ){
                    return reject(err);
                }
                resolve(that);
            } );
        });
    }

    /**
     * @description: 事务回滚
     * @param {type} 
     * @return: 
     */
    rollback(){
        if( ! this._connection ){
            return Promise.reject('当前MySQL连接已经释放, 不能调用 rollback');
        }
        let that = this;
        return new Promise( (resolve, reject) => {
            this._connection.rollback( function(err){
                if( err ){
                    return reject(err);
                }
                resolve(that);
            } );
        });
    }

}